package other.edan.system.k3;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.Campaign;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.service.XObjectService;
import com.rkhd.platform.sdk.service.XoqlService;
import org.apache.commons.lang.StringUtils;
import other.edan.system.client.EdanK3Utils;
import other.edan.system.utils.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description 市场申请审批通过后: 把模版信息推送到k3
 * @Author 黎炎松
 * 2024-06-21 14:30
 */
@RestApi(baseUrl = "/xsy/campaign")
public class PushCampaign implements ApprovalEvent {
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "市场申请审批通过后: 把模版信息推送到k3 ==> ";

    @Override
    public ApprovalEventResponse execute(ApprovalEventRequest request) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + " 触发开始 ");
        logger.info("ObjectApiKey:" + request.getEntityApiKey() + " , DataId:" + request.getDataId());
        logger.info(request.toString());
        ApprovalEventResponse response = new ApprovalEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        pushK3CampaignData(request.getDataId());
        return response;
    }

    /**
     * 手动推送数据到k3
     * @param campaignId
     * @return
     */
    @RestMapping(value = "/syncK3", method = RequestMethod.POST)
    public String syncK3(@RestQueryParam(name = "id") Long campaignId){
        logger.info(LOGGER_MSG + "执行了 '手动推送数据到k3' 按钮事件：" + campaignId);
        return pushK3CampaignData(campaignId);
    }

    /**
     * 批量作废K3申请活动
     * @param campaignIds
     * @return
     */
    @RestMapping(value = "/patchCancelCampaign", method = RequestMethod.POST)
    public String patchCancelCampaign(@RestQueryParam(name = "ids") String campaignIds){
        logger.info(LOGGER_MSG + "执行了 '批量作废K3申请活动' 功能：" + campaignIds);
        return batchCancelK3Campaign(campaignIds);
    }



    public static void main(String[] args) throws ApiEntityServiceException {
        PushCampaign completeAfter = new PushCampaign();
        completeAfter.pushK3CampaignData(3673929697939430L);
        //completeAfter.batchCancelK3Campaign("3343775464184391");
    }

    /**
     * 市场申请模版信息推送到k3
     * @param campaignId
     */
    public String pushK3CampaignData(Long campaignId){
        try {
            logger.info(LOGGER_MSG + "处理开始");

            // 获取市场活动以及所有人信息
            String sql = "select campaignName billname,applicationNumber__c billnumber,ownerId.name applicant,ownerId.employeeCode applicantno,createdAt applydate " +
                    " from campaign where id = " + campaignId;
            QueryResult<JSONObject> query = XoqlService.instance().query(sql, true);
            List<JSONObject> records = query.getRecords();
            logger.info(LOGGER_MSG + "records = " + records);
            if (records.size() <= 0) {
                logger.error(LOGGER_MSG + "查询市场活动数据异常:" + query.getErrorMessage());
                return TfReturnMsgTools.getFailResult("Abnormal query of market activity data");
            }

            // 构造发送的数据
            JSONObject campaign = records.get(0);

            // 获取打印模块url
            JSONObject tempLateData = ComUtils.getTempLateData("campaign", campaignId, 3676337470560594L);
            String tempLateUrl = tempLateData.getString("url");
            if (tempLateUrl != null) {
                tempLateUrl = tempLateUrl.split("\\?")[0];
                campaign.put("fileurl", tempLateUrl);
            }

            // 格式化时间
            String applydate = DateTools.longToString(campaign.getLong("applydate"), "yyyy-MM-dd");
            campaign.put("applydate", applydate);
            logger.info(LOGGER_MSG + "发送的数据 => " + campaign);

            // 记录同步状态
            Campaign upCampaign = new Campaign();
            upCampaign.setId(campaignId);
            upCampaign.setSyncStatus__c(2); // 同步状态 1：待同步 2：成功 3：失败
            upCampaign.setFailureReasons__c("");

            // 发送数据
            ResultBody resultBody = EdanK3Utils.sendPost(campaign, EdanK3Utils.ADD_MARKET_APPLY_URL, "");
            if (!Objects.equals(resultBody.getCode(), "200")) {
                String errMsg = resultBody.getMessage();
                logger.error(LOGGER_MSG + "推送市场活动数据失败:" + errMsg);

                upCampaign.setSyncStatus__c(3); // 同步状态 1：待同步 2：成功 3：失败
                upCampaign.setFailureReasons__c(errMsg); // 失败原因
                OperateResult update = HCXObjectService.update(upCampaign);
                logger.info(LOGGER_MSG + "市场活动更新同步状态: " + update.getSuccess());

                return TfReturnMsgTools.getFailResult("Failed to push market activity data: " + errMsg);
            }

            // 更新同步状态
            OperateResult update = HCXObjectService.update(upCampaign);
            logger.info(LOGGER_MSG + "市场活动更新同步状态: " + update.getSuccess());

            logger.info(LOGGER_MSG + "处理成功");
            return TfReturnMsgTools.getSuccessResult("Push successful");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(LOGGER_MSG + "处理异常:" + e.getMessage());
            return TfReturnMsgTools.getFailResult("Push exception:" + e.getMessage());
        }
    }

    /**
     * 批量关闭k3市场活动
     * @param campaignIds
     * @return
     */
    private String batchCancelK3Campaign(String campaignIds) {
        String LOGGER_MSG_TIPS = "批量关闭k3市场活动 ==> ";
        try {
            logger.info(LOGGER_MSG_TIPS + "处理开始 " + campaignIds);
            if (StringUtils.isBlank(campaignIds)) {
                logger.error(LOGGER_MSG_TIPS + "市场活动ids不可为空");
                return TfReturnMsgTools.getFailResult("Market activity ids cannot be empty");
            }

            // 根据id获取对应的市场活动编码
            String sql = "select id,applicationNumber__c from campaign where id in (" + campaignIds + ")";
            QueryResult<Campaign> query = XObjectService.instance().query(sql);
            List<Campaign> campaignList = query.getRecords();
            logger.info(LOGGER_MSG_TIPS + "campaignList:" + campaignList.size());
            if (campaignList == null || campaignList.size() <= 0) {
                logger.error(LOGGER_MSG_TIPS + "查询市场活动数据异常");
                return TfReturnMsgTools.getFailResult("Abnormal query of market activity data");
            }

            // 修改k3市场活动数据状态
            List<Campaign> upCampaignsList = new ArrayList<>();
            String reqToken = EdanK3Utils.getToken();
            for (Campaign campaign : campaignList) {

                // 构建参数
                JSONObject sendCampaign = new JSONObject();
                sendCampaign.put("billnumber", campaign.getApplicationNumber__c());
                sendCampaign.put("isdelete", "1");

                // 更新同步状态
                Campaign upCampaign = new Campaign();
                upCampaign.setId(campaign.getId());
                upCampaign.setCancelSyncStatus__c(2); // 同步状态 1：待同步 2：成功 3：失败
                upCampaign.setCancelFailureReasons__c("");

                // 发送数据
                ResultBody resultBody = EdanK3Utils.sendPost(sendCampaign, EdanK3Utils.UP_MARKET_APPLY_URL, reqToken);
                if (!Objects.equals(resultBody.getCode(), "200")) {
                    String message = resultBody.getMessage();
                    logger.error(LOGGER_MSG_TIPS + "修改市场活动数据失败:" + message);

                    upCampaign.setCancelSyncStatus__c(3); // 同步状态 1：待同步 2：成功 3：失败
                    upCampaign.setCancelFailureReasons__c(message);
                    //return TfReturnMsgTools.getFailResult("修改市场活动数据失败: " + resultBody.getMessage());
                }

                upCampaignsList.add(upCampaign);
            }

            // 批量更新同步状态
            BatchOperateResult batchOperateResult = HCXObjectService.updateBatch(upCampaignsList);
            logger.info(LOGGER_MSG_TIPS + "批量更新作废同步状态:" + batchOperateResult.getSuccess());


            logger.info(LOGGER_MSG_TIPS + "处理成功");
            return TfReturnMsgTools.getSuccessResult("Processing successful");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(LOGGER_MSG_TIPS + "处理异常:" + e.getMessage());
            return TfReturnMsgTools.getFailResult("Handling exceptions:" + e.getMessage());
        }
    }


}
